<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useVModel } from "@vueuse/core";
import { getDepartmentTreeList, getExternalList } from "@/api/department";

const props = defineProps({
  value: {
    // 选中值
    type: [String, Number],
    default: ""
  },
  disabled: {
    // 是否禁用
    type: Boolean,
    default: false
  },
  leaderUserName: {
    // 禁用时显示的值
    type: String,
    default: ""
  },
  isNeedTab: {
    // 是否需要tab
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(["update:value", "value"]);

const staffList = ref([]);
const outStaffList = ref([]);

const tab = ref(true);
const res = useVModel(props, "value", emits);

defineOptions({
  name: "ChargerSelect"
});

onMounted(() => {
  // 获取内部人员
  getDepartmentTreeList({ showEmployee: false }).then(rsp => {
    staffList.value = (rsp.data || []).map(item => {
      return recircleFn(item);
    });
  });
  // 获取外部人员
  getExternalList().then(rsp => {
    outStaffList.value = rsp.data || [];
  });
});

// 递归人员处理，将人员信息添加到部门中
const recircleFn = item => {
  item.children = (item.children || []).map(val => {
    val.userId = val.id;
    val.disabled = true;
    if (val.children && val.children.length > 0) {
      return recircleFn(val);
    }
    return val;
  });
  if (item.employeeList) {
    item.children = item.employeeList
      .map(val => {
        val.departmentName = val.employeeName;
        return val;
      })
      .concat(item.children || []);
  }
  item.userId = item.id;
  item.disabled = true;
  return item;
};
</script>
<template>
  <div>
    <el-tree-select
      v-if="!props.disabled"
      v-model="res"
      class="tree-select"
      :data="tab ? staffList : outStaffList"
      filterable
      accordion
      clearable
      show-checkbox
      node-key="userId"
      :props="{
        label: tab ? 'departmentName' : 'nickname',
        disabled: 'disabled'
      }"
    >
      <template #header>
        <el-radio-group v-model="tab">
          <el-radio-button :value="true">内部人员</el-radio-button>
          <el-radio-button v-if="isNeedTab" :value="false"
            >外部人员</el-radio-button
          >
        </el-radio-group>
      </template>
      <template #default="{ node, data }">
        <span v-if="tab">{{
          data.departmentName +
          " " +
          (data.employeeName ? data.employeeCode : "")
        }}</span>
        <span v-else>{{ data.nickname + " " + data.userCode }}</span>
      </template>
    </el-tree-select>
    <span v-else>{{ props.leaderUserName }}</span>
  </div>
</template>
<style lang="scss" scoped>
// .el-select {
//   --el-select-width: 256px !important;
// }
</style>
